import { ref, reactive } from 'vue'
import { updatepassword } from "~/api/manager"
import { showModal, toast } from "~/composables/util"
import { useRouter } from "vue-router"
import { useStore } from "vuex"

export function useRepassword() {
    const router = useRouter()
    const store = useStore()
    // 修改密码
    const formDrawerRef = ref(null)
    const form = reactive({
        userId:store.state.user.id,
        password:"",
        newPass: "",
        repassword:""
    })

    const rules = {
        password: [
            {
                required: true,
                message: '旧密码不能为空',
                trigger: 'blur'
            },
        ],
        newPass: [
            {
                required: true,
                message: '新密码不能为空',
                trigger: 'blur'
            },
        ],
        repassword: [
            {
                required: true,
                message: '确认密码不能为空',
                trigger: 'blur'
            },
        ]
    }

    const formRef = ref(null)
    const onSubmit = () => {
        formRef.value.validate((valid) => {
            if (!valid) {
                return false
            }
            if(form.newPass !== form.repassword){
                toast("两次密码不一致", "warning")
                return false
            }
            formDrawerRef.value.showLoading()
            updatepassword(form)
                .then(res=>{
                    if (res.data.code === "600") {
                        toast(res.data.msg, 'error')
                        return false
                    }
                    toast("修改密码成功，请重新登录")
                    store.dispatch("logout")
                    // 跳转回登录页
                    router.push("/login")
                })
                .finally(()=>{
                    formDrawerRef.value.hideLoading()
                })

        })
    }

    const openRePasswordForm = () => formDrawerRef.value.open()

    return {
        formDrawerRef,
        form,
        rules,
        formRef,
        onSubmit,
        openRePasswordForm
    }
}

export function useLogout() {
    const router = useRouter()
    const store = useStore()
    function handleLogout() {
        showModal("是否要退出登录？").then(() => {
            store.dispatch("logout")
            // 跳转回登录页
            router.push("/login")
            // 提示退出登录成功
            toast("退出登录成功")
        })
    }

    return {
        handleLogout
    }
}
